<template>
  <div class="element">
    <div ref="qr_code_test" id="qr_code_test" class="qr_code_test">
      <el-button @click="refresh">刷新</el-button>
      <p style="color: rgb(156, 156, 156)">懒加载（滚动条到底部加载下一次数据） + 虚拟滚动 + 界面可见区域实时更新 + 展开行</p>
      <iframe :src="wxUrl" width="300px" height="400px"></iframe>
    </div>
    <div class="my_table">
      <vxe-table
        border
        height="auto"
        show-overflow
        ref="xTable"
        row-id="listId"
        size="mini"
        :loading="loading"
        :checkbox-config="{reserve: true}"
        :data="tableData"
        @sort-change="sortChange">
        <vxe-column type="checkbox" width="60"></vxe-column>
        <vxe-column field="listId" title="listId"></vxe-column>
        <vxe-column v-for="(item) in 10" :field="'attr' + item" :title="'attr' + item" sortable></vxe-column>
        <vxe-column type="expand" width="80">
          <template #content="{ row, rowIndex }">
            <div style="width: 300px;height: 150px;">
              <ul>
                <li>
                  <span>ID：</span>
                  <span>{{ row }}</span>
                </li>
              </ul>
            </div>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </div>
</template>

<script>
import { httpRequest } from "@/untils/httpRequest";
import _ from "lodash";

export default {
  name: "BigDataCase",
  data() {
    return {
      wxUrl: "",
      loading: false,
      tableData: [],
      sortCfg: {
        property: "",
        order: ""
      },
      tablePage: {
        currentPage: 1,
        pageSize: 500,
        pageSizes: [10, 200, 300],
        totalResult: 0
      },
      timer: null,
      loopIds: [],
      expandRows: []
    };
  },
  methods: {
    // 获取二维码
    getWxQrCode() {
      // let flgRandomNum = Math.random();
      // this.randomNum = String(flgRandomNum);
      // localStorage.setItem("randomNum", String(flgRandomNum));
      let params = {
        appid: "wx55dbf016c113a65c",
        scope: "snsapi_login", //网页授权，目前网页只有这一种方式，静默授权
        redirect_uri: encodeURIComponent(`${document.location.protocol}//clercloud.com/cmc/#/login`)     //回调域名(地址前部分是项目域名，后部分loginSuccess是微信需要跳转的路径（vue中的路由名称）)
        // state: flgRandomNum,
        // style: "black",
        // href: "data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDI2MHB4O30NCi5pbXBvd2VyQm94IC50aXRsZSB7ZGlzcGxheTogbm9uZTt9"
      };
      this.wxUrl = "https://open.weixin.qq.com/connect/qrconnect?appid=" + params.appid + "&scope=" + params.scope + "&redirect_uri=" + params.redirect_uri + "&state=";
      // params.state + "&login_type=jssdk&style=" +
      // params.style + "&href=" +
      // params.href;
      // let qrCodeWrap = document.createElement("iframe");
      // qrCodeWrap.src = this.wxUrl,
      //   qrCodeWrap.frameBorder = "0",
      //   qrCodeWrap.allowTransparency = "true",
      //   qrCodeWrap.scrolling = "no",
      //   qrCodeWrap.width = "300px",
      //   qrCodeWrap.height = "400px";
      // let a = document.getElementById("qr_code_test");
      // let b = this.$refs["qr_code_test"];
      // console.log(a, b);
      // document.getElementById("qr_code_test").appendChild(qrCodeWrap);
      // this.$refs["qr_code_test"].appendChild(qrCodeWrap);
    },
    getData() {
      if (this.timer) {
        clearInterval(this.timer);
      }
      this.loading = true;
      let params = {
        currentPage: 1,
        pageSize: 500,
        property: this.sortCfg.property,
        order: this.sortCfg.order
      };
      return new Promise(resolve => {
        httpRequest("post", "/component/getArticle", null, params, "proxy").then((res) => {
          if (res && res.data.code === 200) {
            this.loading = false;
            let list = res.data.data.list;
            this.tablePage.totalResult = res.data.data.total;
            this.tableData = list;
            resolve();
          }
        }).then(()=>{
          let _this = this;
          let dom = this.$(".my_table .vxe-table--body-wrapper")[0];
          if (!dom) return
          dom.addEventListener("scroll", function() {
            _this.tableScroll(dom);
          });
          _this.loopGetData();
        })
      });
    },
    tableScroll(dom) {
      let _this = this;
      const scrollDistance = dom.scrollHeight - dom.scrollTop - dom.clientHeight;
      if (scrollDistance <= 0) {//等于0证明已经到底，可以请求接口
        if (_this.tablePage.currentPage < Math.ceil(_this.tablePage.totalResult / 500)) {//当前页数小于总页数就请求
          _this.tablePage.currentPage++;//当前页数自增
          let params = {
            currentPage: _this.tablePage.currentPage,
            pageSize: 500,
            property: _this.sortCfg.property,
            order: _this.sortCfg.order,
            lastIds: _this.lastIds
          };
          _this.loading = true;
          httpRequest("post", "/component/getArticle", null, params, "proxy").then((res) => {
            if (res && res.data.code === 200) {
              let list = res.data.data.list;
              _this.tableData = _this.tableData.concat(list);
            }
            _this.loading = false;
          });
        }
      }
    },
    sortChange({ property, order }) {
      this.sortCfg.order = order;
      this.sortCfg.property = order ? property : null;
      this.getData();
    },
    calcLoopIds(dom) {
      if (!this.$refs.xTable?.scrollYStore) return
      let currentViewStartIndex = this.$refs.xTable.scrollYStore.startIndex
      let currentViewEndIndex = this.$refs.xTable.scrollYStore.endIndex
      this.expandRows = this.$refs.xTable.getRowExpandRecords()
      this.loopIds = this.tableData.filter((item, index) => {
        return index >= currentViewStartIndex && index <= currentViewEndIndex;
      }).map((item) => {
        return item.listId;
      });
    },
    loopGetData() {
      let dom = this.$(".my_table .vxe-table--body-wrapper")[0];
      this.calcLoopIds(dom);
      this.expandRows = this.$refs.xTable.getRowExpandRecords()
      var result = []
      this.tableData.forEach((item,index)=>{
        this.expandRows.forEach((sonItem)=>{
          if (item.listId === sonItem.listId) {
            result.push(index)
          }
        })
      })
      let params = {
        currentPage: this.tablePage.currentPage,
        pageSize: 500,
        property: this.sortCfg.property,
        order: this.sortCfg.order,
        loopIds: this.loopIds
      };
      return new Promise(resolve => {
        httpRequest("post", "/component/getArticle", null, params, "proxy").then((res) => {
          if (res && res.data.code === 200) {
            let list = res.data.data.list;
            list.forEach(item=>{
              item.attr1 = item.attr1 + 'dasd'
            })
            this.tableData.forEach((item,index)=>{
              list.forEach(sonItem =>{
                if (item.listId === sonItem.listId) {
                  this.tableData.splice(index,1,sonItem)
                  this.tableData[index] = sonItem
                }
              })
            })
            this.$nextTick(()=>{
              result.map((item)=>{
                this.$refs.xTable.setRowExpand([this.tableData[item]], true)
              })
            })
            if (this.timer) {
              clearTimeout(this.timer);
            }
            this.timer = setTimeout(() => {
              this.loopGetData();
            }, 10000);
            resolve();
          }
        });
      });
    },
    refresh() {
      this.getData()
    }
  },
  computed: {},
  mounted() {
    this.getData()
    this.getWxQrCode()
    window.addEventListener('scroll',()=>{
      let dom = this.$(".my_table .vxe-table--body-wrapper")[0];
      this.calcLoopIds(dom);
    })
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }
};
</script>

<style scoped>
.element {
  width: 100%;
  height: 100%;
  padding: 20px;
  display: flex;
}

.my_table {
  margin-left: 10px;
  width: 100%;
  height: calc(100vh - 120px);
}
</style>